<?php
namespace app\admin\controller;


use app\common\logic\Users;
use app\common\model\Check;
use app\common\model\LoginLog;
use app\common\model\MoneyDetail;
use app\common\model\MyPackage;
use app\common\service\App;
use Monolog\Handler\DynamoDbHandler;
use think\Db;
use think\Exception;
use think\Request;


class User extends Base
{

    function _initialize()
    {
        parent::_initialize();
        $this->assign('stamp',123);
    }

    public function index()
    {
        $where = [];
        if(!empty($_GET['nick_name'])){
            $where['nick_name|phone'] = ['like','%'.trim(input('get.nick_name')).'%'];
        }
        if(!empty($_GET['uuid'])){
            $where['uuid'] = trim(input('get.uuid'));
        }
        if(!empty($_GET['user_id'])){
            $where['user_id'] = trim(input('get.user_id'));
        }

        if(!empty($_GET['startDate'])){
            $startDate = strtotime(trim(input('get.startDate')));
        }
        if(!empty($_GET['endDate'])){
            $endDate = strtotime(trim(input('get.endDate')));
        }
//        dd($startDate,$endDate);
        if($startDate&&$endDate){
            $where['create_time'] = ['between',[$startDate,$endDate]];
        }else if($startDate&&empty($endDate)){
            $where['create_time'] = ['>',$startDate];
        }else if($endDate&&empty($startDate)){
            $where['create_time'] = ['<',$endDate];
        }


        $model = new \app\common\model\Users();
        $money = $model->sum('money');
        $cash  = $model->sum('cash');
        $gift_coin = $model->sum('gift_coin');
        $rows = $model->userList($where);
        $this->assign([
            'title' => '用户管理',
            'rows' => $rows,
            'money' => $money,
            'cash' => $cash,
            'gift_coin' => $gift_coin,
            'pageHTML' => $rows->render(),
        ]);
        return view();
    }


    public function change_money()
    {
        $data = input('param.');
        if (!is_numeric($data['user_id'])){
            $data['user_id'] = dehashid($data['user_id']);
        }
        if (empty($data['remark'])){
            $this->error('备注不能为空');
        }
        $user = \app\common\model\Users::where('user_id',$data['user_id'])->find();
        if (isInt($data['user_id'])){
            Db::startTrans();
            try{
                if ($data['money'] >= 1){

                    //写入资金明细
                    money_detail(1,$data['user_id'],'后台充值'.$data['money'].'钻',$data['money'],'充值');

                    //写入充值记录
                    $item['user_id']     = $data['user_id'];
                    $item['money']       = bcdiv($data['money'],100,0);
                    $item['remark']      = '哈尼'.$data['money'].'钻充值(后台增加)';
                    $item['status']      = 1;
                    $item['type']        = 1;
                    $item['create_time'] = time();
                    $item['update_time'] = time();
                    $item['trade_type']  = 8;
                    Db::name('bankroll')->strict(false)->insert($item);

                    $proxy_id = App::staticInfo('proxy_id',$data['user_id']);
                    $create_time = App::staticInfo('create_time',$data['user_id']);

                    if ($proxy_id && (time() - $create_time) <= (86400 * 31)){

                        $jewel =  App::getExtend('jewel');
                        $ratio = $jewel/100;
                        $item['jewel']       = $data['money'] * $ratio;
                        if ($item['jewel'] <=1){
                            return;
                        }
                        $title = sprintf('推荐新用户充值%s钻获得返利%s钻[%s]',$data['money'],$item['jewel'],$jewel.'%');
                        money_detail(1,$proxy_id,$title,$item['jewel'],'锁定');
                        Db::name('users')->where('user_id',$proxy_id)->setInc('spread_total',$item['jewel']);
                        Db::name('users')->where('user_id',$proxy_id)->setInc('spread_cash',$item['jewel']);
                        App::sendUsrMsg('system',hashid($proxy_id),$title);
                    }else{
                        $item['jewel']  = 0;
                    }
                }



                Db::name('users')->where('user_id',$data['user_id'])->setInc('money',$data['money']);
                Db::name('users')->where('user_id',$data['user_id'])->setInc('coin',$data['coin']);
                Db::name('users')->where('user_id',$data['user_id'])->setInc('gift_coin',$data['gift_coin']);
                Db::name('users')->where('user_id',$data['user_id'])->setInc('cash',$data['cash']);
                $user2 = \app\common\model\Users::where('user_id',$data['user_id'])->find();
                $params =
                    sprintf('修改用户[%s][user_id:%s]钱包余额:大神收益%s(%s)为:%s;钻石%s(%s)为:%s;金币余额%s(%s)为:%s;礼物收益%s(%s)为:%s;备注内容:',
                        $user['nick_name'],$data['user_id'],$user['cash'],$data['cash'],$user2['cash'],
                        $user['money'],$data['money'],$user2['money'],$user['coin'],$data['coin'],$user2['coin'],
                        $user['gift_coin'],$data['gift_coin'],$user2['gift_coin'],$data['remark']
                        )
                ;
                $log['params']      = $params;
                $log['user_id']     = session('user_id');
                $log['url']         = request()->url();
                $log['title']       = '修改用户余额';
                $log['create_time'] = time();
                $log['update_time'] = time();
                $log['ip']          = request()->ip();
                Db::name('action_log')->insert($log);

                Db::commit();

            }catch (\Exception $e){
                Db::rollback();
                $this->error($e->getMessage());
            }

            $this->success('操作成功');
        };
        $this->error('操作失败');
    }


    /**
     * @return \think\response\View
     * 用户信息编辑
     */
    public function user_edit()
    {
        if(request()->isPost()){
            $data  = input('post.');
            $model = new Users();
            if (!empty($data['phone'])){
                $phone = Db::name('users')
                    ->where('phone',$data['phone'])
                    ->where('user_id','<>',$data['id'])
                    ->value('user_id');
                if ($phone){
                    $this->error('该手机号已注册');
                }
            }
            if (!empty($data['uuid'])){
                $phone = Db::name('users')
                    ->where('uuid',$data['uuid'])
                    ->where('user_id','<>',$data['id'])
                    ->value('user_id');
                if ($phone){
                    $this->error('账号已存在');
                }
            }

//            dump($data);exit;
            $result = $model->saveChange($data);
            if($result){
                $this->success('操作成功',url('user/index'));
            }
            $this->error($model->getError());
        }
        $this->_show('users','user_id');
        $this->assign([
            'title' => '用户信息编辑',
        ]);
        return view();
    }

    public function change()
    {
        $data = input();
        $data['id'] = dehashid($data['id']);
        $result = Db::name('users')->update(['status'=>$data['type'],'user_id'=>$data['id']]);
        if($result !== false){
            \app\api\controller\Base::outRoomFunc($data['id'],\app\api\controller\Base::staticInfo('room_id',$data['id']));
            //改变用户状态后清空前端token
            cache('token_'.hashid($data['id']),null);
            if ($data['type'] == 0){

                //封禁用户发送封禁消息
                $this->banedUser($data['id'],$data['end_time']);
            }
            $this->success('操作成功');
        }
        $this->error('操作失败');
    }

    public function user_pass()
    {
        $id     = input('param.id');
        $result = Db::name('users')->where('user_id',$id)->delete();
        if ($result){
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }








    /**
     * 登陆日志列表
     */
    public function log()
    {
        $where = [];
        if(!empty($_GET['nick_name'])){
            $where['c.nick_name'] = ['like','%'.trim(input('get.nick_name')).'%'];
        }

        if (is_numeric(input('uuid'))){
            $map['c.uuid'] =  ['like','%'.trim(input('get.uuid')).'%'];
        }

        $model = new LoginLog();
        $rows = $model->getList($where);
        $this->assign([
            'rows' => $rows,
            'pageHTML' => $rows->render(),
        ]);
        return view();
    }

    public function del()
    {
        $id     = input('param.id');
        $result = Db::name('login_log')->delete($id);
        if ($result){
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }

    public function cate()
    {
        $this->_list2('users_category','create_time DESC');
        $this->assign([
            'title'=>'用户类型'
        ]);
        return view();
    }

    public function cate_edit()
    {
        if (request()->isPost()){
            $data   = input('post.');
            $result = Db::name('users_category')->strict(false)->where('cid',$data['id'])->update($data);
            if($result!==false){
                $this->success('保存成功','/user/cate');
            }
            $this->error('操作失败');
        }
        $this->_show('users_category','cid');
        return view();
    }



    /**
     * 用户资金明细列表
     */
    public function detail()
    {
        $id = $this->request->param('id');
        $where = [];
        if (is_numeric($id)){
            $where['a.user_id'] = $id;
        }
        $where['a.status'] = 1;

        if (input('title') == 'fl'){
            $where['a.title'] =  ['like','%推荐新用户充值%'];
        }

        if (is_numeric(input('uuid'))){
            $where['u.uuid'] = input('uuid');
        }

        if (is_numeric(input('type'))){
            $where['a.type'] = input('type');
        }

        if(!empty($_GET['nick_name'])){
            $where['nick_name|phone'] = ['like','%'.trim(input('get.nick_name')).'%'];
        }

        if(!empty($_GET['start'])&&empty($_GET['end'])){
            $where['a.create_time'] = ['>=',strtotime($_GET['start'])];
        }elseif(!empty($_GET['end'])&&empty($_GET['start'])){
            $where['a.create_time'] = ['<=',strtotime($_GET['end'])];
        }elseif(!empty($_GET['start'])&&!empty($_GET['end'])){
            $where['a.create_time'] = ['between',array(strtotime($_GET['start']),strtotime($_GET['end']))];
        }
        $model = new MoneyDetail();
        $rows = $model->money_detail_list($where);
        $where['a.type'] = 1;
        $inc = $model->alias('a')->join('users u','a.user_id = u.user_id','LEFT')->where($where)->sum('a.money');
        $where['a.type'] = 2;
        $dec = $model->alias('a')->join('users u','a.user_id = u.user_id','LEFT')->where($where)->sum('a.money');
        $this->assign([
            'title' => '资金明细',
            'rows' => $rows,
            'pageHTML' => $rows->render(),
            'inc' => $inc,
            'dec' => $dec,
        ]);
        return view('money_detail');
    }


    /**
     * 用户包裹明细
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function package()
    {
        $id = $this->request->param('id');
        $where = [];
        if (is_numeric($id)){
            $where['p.user_id'] = $id;
        }

        if (is_numeric(input('uuid'))){
            $where['u.uuid'] = input('uuid');
        }

        if (is_numeric(input('type'))){
            $where['p.type'] = input('type');
        }

        if(!empty($_GET['nick_name'])){
            $where['u.nick_name|u.phone'] = ['like','%'.trim(input('get.nick_name')).'%'];
        }

        if(!empty($_GET['start'])&&empty($_GET['end'])){
            $where['a.create_time'] = ['>=',strtotime($_GET['start'])];
        }elseif(!empty($_GET['end'])&&empty($_GET['start'])){
            $where['a.create_time'] = ['<=',strtotime($_GET['end'])];
        }elseif(!empty($_GET['start'])&&!empty($_GET['end'])){
            $where['a.create_time'] = ['between',array(strtotime($_GET['start']),strtotime($_GET['end']))];
        }
        $model = new MyPackage();

//        dd($where);


        $where['u.user_id'] = ['neq',0];
//        $where['d.status'] = 1;
        $rows = $model->getRows1($where);
//        $where['a.type'] = 1;
//        $inc = $model->alias('a')->join('users u','a.user_id = u.user_id','LEFT')->where($where)->sum('a.money');
//        $where['a.type'] = 2;
//        $dec = $model->alias('a')->join('users u','a.user_id = u.user_id','LEFT')->where($where)->sum('a.money');
        $this->assign([
            'title' => '资金明细',
            'rows' => $rows,
            'pageHTML' => $rows->render(),
//            'inc' => $inc,
//            'dec' => $dec,
        ]);
        return view();
    }

    public function package_edit()
    {
        if (request()->isPost()) {
            $id = input('post.id');
            $data = Db::name('my_package')->where('p_id', $id)->update(['num' => input('num'), 'update_time' => time()]);
            if ($data !== false) $this->success('操作成功');
            $this->error('操作失败');
        }

        $id = Request::instance()->param('id');
        $where = [];
        if (is_numeric($id)){
            $where['p.p_id'] = $id;
        }

        $model = new MyPackage();
        $data = $model->getOne($where);
        $this->assign('data', $data);
        $this->assign('title', 'bug反馈');
        return view();
    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 发送极光推送
     */
    public function push()
    {
        if (request()->isPost()){
            $data = input('post.');
            $push_id = 'all';

            if ($data['type'] == 2){
                //推送给用户(极光推送)
                if (is_numeric($data['user_id'])){
                    $push_id = Db::name('user_extend')->where('user_id',$data['user_id'])->value('j_push_id');
                    if (empty($push_id)) $this->error('推送失败,用户无推送id');
                }

                $result = j_push($data['title'],$push_id);
            }else{

                $result = \app\api\controller\Base::sendRoomMsg('all','push',$data['title']);
            }


            if ($result){
                $this->success('发布成功');
            }
        }
        $this->error('系统繁忙,请稍后重试');
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 修改审核列表
     */
    public function check()
    {
        $model = new Check();
        $map   = [];
        if (input('nick_name')){
            $map['u.nick_name'] = ['like','%'.trim(input('nick_name')).'%'];
        }
        if (is_numeric( input('status'))){
            $map['a.status'] = input('status');
        }
        if (is_numeric(input('uuid'))){
            $map['u.uuid'] =  input('get.uuid');
        }


        $rows  = $model->getList($map);
        $this->assign([
            'title' => '修改审核列表',
            'pageHTML' => $rows->render(),
            'rows' => $rows,
        ]);
        return view();
    }

    public function edit()
    {
        $data = input();
        $info = Db::name('check')->where('check_id',$data['id'])->findOrFail();

        Db::startTrans();
        try{
            if ($data['status'] == 0){  //未通过审核  回滚数据
                switch ($info['type']){
                    case 1:
//                        Db::name('users')->where('user_id',$info['user_id'])->update(['header_img'=>$info['before']]);
                        $str = sprintf('您于%s修改的头像因不符合规范系统已驳回',date('Y-m-d H:i',$info['create_time']));
                        //发送系统消息
                        \app\api\controller\Base::sendUsrMsg('system',hashid($info['user_id']),$str);
                        break;
                    case 2:
//                        if (!is_numeric($info['extend'])){
//                            $this->error('参数错误');
//                        }
                        if (empty($info['before'])){
//                            Db::name('user_img')->where('img_id',$info['extend'])->delete();
                            $str = sprintf('您于%s添加的形象照因不符合规范系统已驳回',date('Y-m-d H:i',$info['create_time']));
                            //发送系统消息
                            \app\api\controller\Base::sendUsrMsg('system',hashid($info['user_id']),$str);
                        }else{
//                            Db::name('user_extend')->where('user_id',$info['user_id'])->update(['imgs'=>$info['before']]);
                            $str = sprintf('您于%s修改的形象照因不符合规范系统已驳回',date('Y-m-d H:i',$info['create_time']));
                            //发送系统消息
                            \app\api\controller\Base::sendUsrMsg('system',hashid($info['user_id']),$str);
                        }
                        break;
                    case 3:
                        Db::name('users')->where('user_id',$info['user_id'])->update(['sign'=>$info['before']]);
                        $str = sprintf('您于%s修改的签名因不符合规范系统已驳回',date('Y-m-d H:i',$info['create_time']));
                        //发送系统消息
                        \app\api\controller\Base::sendUsrMsg('system',hashid($info['user_id']),$str);
                        break;
                    case 4:
                        Db::name('users')->where('user_id',$info['user_id'])->update(['nick_name'=>$info['before']]);
                        $str = sprintf('您于%s修改的昵称因不符合规范系统已驳回',date('Y-m-d H:i',$info['create_time']));
                        //发送系统消息
                        \app\api\controller\Base::sendUsrMsg('system',hashid($info['user_id']),$str);
                        break;
                }

            }else{
                //通过审核
                switch ($info['type']){
                    case 1:
                        Db::name('users')->where('user_id',$info['user_id'])->update(['header_img'=>$info['after']]);
                        $str = sprintf('您于%s修改的头像系统已通过',date('Y-m-d H:i',$info['create_time']));
                        \app\api\controller\Base::sendUsrMsg('system',hashid($info['user_id']),$str);
                        break;
                    case 2:
                        Db::name('user_extend')->where('user_id',$info['user_id'])->update(['imgs'=>$info['after']]);
                        $str = sprintf('您于%s修改的形象照系统已通过',date('Y-m-d H:i',$info['create_time']));
                        //发送系统消息
                        \app\api\controller\Base::sendUsrMsg('system',hashid($info['user_id']),$str);
                        break;
                }
            }

            Db::name('check')->whereOr('check_id',$data['id'])->update(['status'=>$data['status']]);
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('操作成功');
    }





    public function package_del()
    {
        $this->_del('my_package');
    }


    public function delete()
    {
        $this->_del('check');
    }

}
